<?php

use App\Exceptions\InvalidRequestException;
use App\Helper\KeysHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use SuperEggs\DcatDistpicker\DcatDistpickerHelper;

if (!function_exists('successReturn')) {
    function successReturn($data = [], $code = Response::HTTP_OK, $msg = 'successful'): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
}

if (!function_exists('failReturn')) {
    function failReturn($msg, $code = Response::HTTP_BAD_REQUEST): JsonResponse
    {
        $code = $code ?: Response::HTTP_BAD_REQUEST;
        return response()->json([
            'code' => $code,
            'msg' => $msg,
        ], $code);
    }
}


if (!function_exists('getRandomStr')) {
    function getRandomStr($len = 32, $special = false): string
    {
        $chars = [
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z",
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
        ];

        if ($special) {
            $chars = array_merge($chars, [
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", ",",
            ]);
        }

        $charsLen = count($chars) - 1;
        shuffle($chars); //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)]; //随机取出一位
        }
        return $str;
    }
}


/**
 * 文件大小显示转换
 * @param int $size b
 * @return string
 */
if (!function_exists('getRealSize')) {
    function getRealSize(int $size): string
    {
        $b = 1024;
        $kb = 1024 * $b;
        $mb = 1024 * $kb;
        $gb = 1024 * $mb;

        if ($size < $b) {
            return $size . 'B';
        } elseif ($size < $kb) {
            return round($size / $b, 2) . 'KB';
        } elseif ($size < $mb) {
            return round($size / $kb, 2) . 'MB';
        } elseif ($size < $gb) {
            return round($size / $mb, 2) . 'GB';
        } else {
            return round($size / $gb, 2) . 'TB';
        }
    }
}


/**
 * 获取可访问的阿里云对象存储地址
 * @param string $path 视频地址
 * @param int $expiration_hour 链接有效期，单位：小时
 */
if (!function_exists('getAliOssUrl')) {
    function getAliOssUrl($path, $expiration_hour = 1): string
    {
        $storage = Storage::disk('oss');
        return $storage->temporaryUrl($path, now()->addHours($expiration_hour));
    }
}

//把带w的数量转成普通数量
function wTransformNumber(string $number): float|int|string
{
    if (str_contains($number, 'w')) {
        return \Illuminate\Support\Str::replace('w', '', $number) * 10000;
    }
    return $number;
}

//将很大的数字转换成带w的格式
function numberTransformW(string $number): float|int|string
{
    if ($number >= 10000) {
        return $number / 10000 . 'w';
    }
    return $number;
}


if (!function_exists('getBoolOption')) {
    //获取布尔值的选择项
    function getBoolOption(): array
    {
        return [
            0 => '否',
            1 => '是'
        ];
    }
}


if (!function_exists('sendLoginSms')) {
    /**
     * 发送登录短信验证码
     * @param string $phone
     * @param string $code
     * @param string $type
     * @throws InvalidRequestException
     */
    function sendLoginSms(string $phone, string $code, string $type)
    {
        $config = config('sms');
        $content = sprintf($config[$type], $code);
        try {
            $response = \Illuminate\Support\Facades\Http::asForm()->post('http://dc.28inter.com/sms.aspx', [
                'userid' => $config['userid'],//企业id
                'account' => $config['account'],//帐号
                'password' => $config['password'],//密码
                'mobile' => $phone,//接收手机号
                'content' => '【' . $config['sign'] . '】' . $content,//发送内容
                'sendTime' => '',
                'action' => 'send',
                'extno' => '',
                'rt' => 'json'
            ]);
            $json = $response->json();
            if ($json['ReturnStatus'] == 'Faild') {
                throw new InvalidRequestException($json['Message']);
            }
            //发送成功，code存入缓存
            $key = match ($type) {
                'login' => sprintf(KeysHandler::LOGIN_SMS_CODE, $phone),
                'register' => sprintf(KeysHandler::REGISTER_SMS_CODE, $phone),
                'reset_password' => sprintf(KeysHandler::RESET_PASSWORD_SMS_CODE, $phone),
            };
            Cache::set($key, $code, KeysHandler::LOGIN_SMS_CODE_TTL);
        } catch (Exception $exception) {
            throw new InvalidRequestException($exception->getMessage());
        }
    }
}


if (!function_exists('checkLoginSms')) {
    /**
     * 校验登录短信验证码是否正确
     * @param $phone
     * @param $code
     * @param $type
     * @return bool
     */
    function checkLoginSms($phone, $code, $type): bool
    {
        $key = match ($type) {
            'login' => sprintf(KeysHandler::LOGIN_SMS_CODE, $phone),
            'register' => sprintf(KeysHandler::REGISTER_SMS_CODE, $phone),
            'reset_password' => sprintf(KeysHandler::RESET_PASSWORD_SMS_CODE, $phone),
        };
        $check = Cache::get($key) === $code;
        if ($check) {
            //校验正确，清空验证码
            Cache::forget($key);
        }
        return $check;
    }
}

if (!function_exists('getAreaName')) {
    /**
     * 根据省市区code获取名称
     * @param $code
     * @return string
     */
    function getAreaName($code): string
    {
        return DcatDistpickerHelper::getAreaName($code);
    }
}

if (!function_exists('onlyOrderSn')) {
    function onlyOrderSn(): string
    {
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //生成唯一订单号
        return $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    }
}













